package com.ai.dmc.index.base.sequence;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.ai.dmc.index.base.impl.base.BaseServiceImpl;
import com.ai.dmc.index.common.exception.BusinessException;

/**
 * 
 * Title： 获取指标列号的公用类 Description： 提供获取指标当前和下一指标序列号的方法 Copyright：Copyright (c)
 * 2009 Company：北京亚信智慧数据科技有限公司
 * 
 * @author xc, Jan 16, 2016
 * @version 1.0
 */
public class SequenceGenerator extends BaseServiceImpl {

    private static Set<String> set = Collections.synchronizedSet(new HashSet<String>());

    /**
     * 获取下一个序列
     * 
     * @param modeCode
     * @return
     * @throws BusinessException 
     */
    public String getNextValue(String modeCode) {
        BigDecimal currValue = null;
        try {
            while (set.contains(modeCode)) {
                // wait
            }
            set.add(modeCode);

            Map<String, String> param = new HashMap<>();
            param.put("modeCode", modeCode);
            @SuppressWarnings("unchecked")
            Map<String, Object> datas = (Map<String, Object>) getBaseDao().queryForObject("Sequence.getCurrValue",
                    param);
            BigDecimal stepLength = null;
            if (null != datas && datas.size() > 0) {
                currValue = new BigDecimal(datas.get("currValue").toString());
                stepLength = new BigDecimal(datas.get("stepLength").toString());
                currValue = currValue.add(stepLength);
            }
            if (currValue != null) {
                param.put("currValue", currValue.toString());
                getBaseDao().update("Sequence.updateCurrValue", param);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            set.remove(modeCode);
        }
        return currValue == null ? null : currValue.toString();
    }

    /**
     * 获取当前序列
     * 
     * @param modeCode
     * @return
     */
    public String getCurrValue(String modeCode) {
        try {
            while (set.contains(modeCode)) {
                // wait
            }
            set.add(modeCode);
            Map<String, String> param = new HashMap<>();
            param.put("modeCode", modeCode);
            @SuppressWarnings("unchecked")
            Map<String, Object> datas = (Map<String, Object>) getBaseDao().queryForObject("Sequence.getCurrValue",
                    param);
            if (null != datas && datas.size() > 0) {
                set.remove(modeCode);
                return datas.get("currValue").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            set.remove(modeCode);
        }
        return null;
    }
}
